export default {

  inserted(el, binding) {
    initStickyHeader(el, binding);
  },

  componentUpdated(el, binding) {
    // 当组件更新时重新初始化（处理keep-alive切换回来的情况）
    if (el._stickyHeader) {
      cleanupStickyHeader(el);
    }
    initStickyHeader(el, binding);
  },

  unbind(el) {
    cleanupStickyHeader(el);
  }

};

function initStickyHeader(el, binding) {
  const { value = {} } = binding;
  const offset = value.offset || 0;
  const zIndex = value.zIndex || 1000;
  const shadow = value.shadow !== false;
  const scrollContainer = value.scrollContainer || null;

  const table = el.querySelector('.el-table__header-wrapper');
  if (!table) return;

  // 为每个表格实例创建唯一ID
  const instanceId = 'sticky-header-' + Math.random().toString(36).substr(2, 9);
  el.dataset.stickyInstanceId = instanceId;

  // 保存原始样式和类名
  const originalStyles = {
    position: table.style.position,
    top: table.style.top,
    zIndex: table.style.zIndex,
    width: table.style.width,
    background: table.style.background,
    overflowX: table.style.overflowX,
    boxShadow: table.style.boxShadow,
    left: table.style.left
  };
  const originalClasses = table.className;

  // 创建独立滚动条容器
  const scrollBarContainer = document.createElement('div');
  scrollBarContainer.className = 'el-table-sticky-scrollbar';
  scrollBarContainer.dataset.forTable = instanceId;

  Object.assign(scrollBarContainer.style, {
    position: 'fixed',
    left: '0',
    bottom: '0',
    height: '17px',
    zIndex: zIndex + 1,
    overflowX: 'auto',
    overflowY: 'hidden',
    display: 'none',
    backgroundColor: '#fff',
    boxShadow: shadow ? '0 2px 4px rgba(0, 0, 0, 0.12)' : 'none'
  });

  const scrollContent = document.createElement('div');
  scrollContent.style.height = '1px';
  scrollBarContainer.appendChild(scrollContent);
  document.body.appendChild(scrollBarContainer);

  // 设置基础样式
  Object.assign(table.style, {
    background: '#fff',
    transition: 'all 0.3s',
    overflowX: 'hidden'
  });

  // 获取滚动容器
  const getScrollContainer = () => {
    if (scrollContainer) {
      return typeof scrollContainer === 'string'
        ? document.querySelector(scrollContainer)
        : scrollContainer;
    }

    let parent = el.parentElement;
    while (parent && parent !== document.body) {
      const overflowY = window.getComputedStyle(parent).overflowY;
      if (overflowY === 'auto' || overflowY === 'scroll') {
        return parent;
      }
      parent = parent.parentElement;
    }
    return window;
  };

  const container = getScrollContainer();
  let isSyncingScroll = false;

  // 处理固定列
  const handleFixedColumns = (shouldSticky) => {
    const fixedColumns = el.querySelectorAll('.el-table__fixed, .el-table__fixed-right');

    fixedColumns.forEach((fixedCol) => {
      if (shouldSticky) {
        fixedCol.style.top = offset + 'px';
        fixedCol.style.zIndex = zIndex - 1;

        const fixedHeader = fixedCol.querySelector('.el-table__fixed-header-wrapper');
        if (fixedHeader) {
          fixedHeader.style.top = offset + 'px';
          fixedHeader.style.zIndex = zIndex + 1;

          const headerCells = el.querySelectorAll('th.is-hidden>div.cell');
          headerCells.forEach(cell => {
            cell.style.visibility = 'visible';
          });
        }
      } else {
        fixedCol.style.top = '';
        fixedCol.style.zIndex = '';

        const fixedHeader = fixedCol.querySelector('.el-table__fixed-header-wrapper');
        if (fixedHeader) {
          fixedHeader.style.top = '';
          fixedHeader.style.zIndex = '';

          const headerCells = fixedCol.querySelectorAll('th.is-hidden>div.cell');
          headerCells.forEach(cell => {
            cell.style.visibility = '';
          });
        }
      }
    });
  };

  // 更新浮动滚动条
  const updateFloatingScrollbar = (tableRect) => {
    const bodyWrapper = el.querySelector('.el-table__body-wrapper');
    if (!bodyWrapper) return;

    scrollBarContainer.style.width = tableRect.width + 'px';
    scrollBarContainer.style.left = tableRect.left + 'px';

    const scrollWidth = bodyWrapper.scrollWidth;
    scrollContent.style.width = scrollWidth + 'px';

    if (!isSyncingScroll) {
      isSyncingScroll = true;
      scrollBarContainer.scrollLeft = bodyWrapper.scrollLeft;
      isSyncingScroll = false;
    }
  };

  // 滚动同步
  const syncScrollFromBar = () => {
    const bodyWrapper = el.querySelector('.el-table__body-wrapper');
    if (bodyWrapper && !isSyncingScroll) {
      isSyncingScroll = true;
      bodyWrapper.scrollLeft = scrollBarContainer.scrollLeft;
      isSyncingScroll = false;
    }
  };

  const syncScrollFromTable = () => {
    if (scrollBarContainer.style.display === 'block' && !isSyncingScroll) {
      const bodyWrapper = el.querySelector('.el-table__body-wrapper');
      if (bodyWrapper) {
        isSyncingScroll = true;
        scrollBarContainer.scrollLeft = bodyWrapper.scrollLeft;
        isSyncingScroll = false;
      }
    }
  };

  scrollBarContainer.addEventListener('scroll', syncScrollFromBar);

  // 主滚动处理函数
  const scrollHandler = () => {
    window.requestAnimationFrame(() => {
      // 只处理当前可见的表格
      if (el.style.display === 'none') {
        // 恢复隐藏表格的原始状态
        Object.assign(table.style, originalStyles);
        table.className = originalClasses;
        scrollBarContainer.style.display = 'none';

        // 恢复固定列
        const fixedColumns = el.querySelectorAll('.el-table__fixed, .el-table__fixed-right');
        fixedColumns.forEach((fixedCol) => {
          fixedCol.style.top = '';
          fixedCol.style.zIndex = '';

          const fixedHeader = fixedCol.querySelector('.el-table__fixed-header-wrapper');
          if (fixedHeader) {
            fixedHeader.style.top = '';
            fixedHeader.style.zIndex = '';
          }
        });

        // 恢复body wrapper
        const bodyWrapper = el.querySelector('.el-table__body-wrapper');
        if (bodyWrapper) {
          bodyWrapper.style.marginTop = '';
        }

        return;
      }

      // 处理可见表格
      const rect = el.getBoundingClientRect();
      const containerRect = container === window
        ? { top: 0, bottom: window.innerHeight }
        : container.getBoundingClientRect();

      const shouldSticky = rect.top - containerRect.top <= offset;
      console.log("shouldSticky", shouldSticky)
      const isAtBottom = container === window
        ? window.innerHeight + window.scrollY >= document.body.scrollHeight
        : container.scrollTop + container.clientHeight >= container.scrollHeight - 60;

      const bodyWrapper = el.querySelector('.el-table__body-wrapper');
      const hasHorizontalScroll = bodyWrapper ?
        bodyWrapper.scrollWidth > bodyWrapper.clientWidth : false;

      if (shouldSticky) {
        Object.assign(table.style, {
          position: 'fixed',
          top: (containerRect.top + offset) + 'px',
          zIndex: zIndex,
          width: rect.width + 'px',
          boxShadow: shadow ? '0 2px 4px rgba(0, 0, 0, 0.12)' : 'none',
          left: rect.left + 'px'
        });

        if (bodyWrapper) {
          bodyWrapper.style.marginTop = table.offsetHeight + 'px';
          scrollBarContainer.style.display = (!isAtBottom && hasHorizontalScroll) ? 'block' : 'none';
          updateFloatingScrollbar({
            width: rect.width,
            left: rect.left,
            height: table.offsetHeight
          });
        }
      } else {
        Object.assign(table.style, originalStyles);
        if (bodyWrapper) {
          bodyWrapper.style.marginTop = '';
          scrollBarContainer.style.display = 'none';
        }
      }

      handleFixedColumns(shouldSticky);
    });
  };

  // 初始化执行
  scrollHandler();

  // 添加事件监听
  container.addEventListener('scroll', scrollHandler, { passive: true });
  window.addEventListener('resize', scrollHandler, { passive: true });

  const bodyWrapper = el.querySelector('.el-table__body-wrapper');
  if (bodyWrapper) {
    bodyWrapper.addEventListener('scroll', syncScrollFromTable, { passive: true });
  }

  // 保存引用以便清理
  el._stickyHeader = {
    scrollHandler,
    originalStyles,
    originalClasses,
    container,
    scrollBarContainer,
    syncScrollFromBar,
    syncScrollFromTable,
    bodyWrapperScrollListener: syncScrollFromTable,
    instanceId
  };
}
function cleanupStickyHeader(el) {
  if (!el._stickyHeader) return;

  const {
    scrollHandler,
    container,
    originalStyles,
    originalClasses,
    scrollBarContainer,
    syncScrollFromBar,
    bodyWrapperScrollListener,
    instanceId
  } = el._stickyHeader;

  // 移除事件监听
  container.removeEventListener('scroll', scrollHandler);
  window.removeEventListener('resize', scrollHandler);
  scrollBarContainer.removeEventListener('scroll', syncScrollFromBar);

  const bodyWrapper = el.querySelector('.el-table__body-wrapper');
  if (bodyWrapper && bodyWrapperScrollListener) {
    bodyWrapper.removeEventListener('scroll', bodyWrapperScrollListener);
  }

  // 恢复表格样式
  const table = el.querySelector('.el-table__header-wrapper');
  if (table) {
    Object.assign(table.style, originalStyles);
    table.className = originalClasses;
  }

  // 恢复固定列样式
  const fixedColumns = el.querySelectorAll('.el-table__fixed, .el-table__fixed-right');
  fixedColumns.forEach((fixedCol) => {
    fixedCol.style.top = '';
    fixedCol.style.zIndex = '';

    const fixedHeader = fixedCol.querySelector('.el-table__fixed-header-wrapper');
    if (fixedHeader) {
      fixedHeader.style.top = '';
      fixedHeader.style.zIndex = '';
    }
  });

  // 移除滚动条
  if (scrollBarContainer && scrollBarContainer.parentNode) {
    scrollBarContainer.parentNode.removeChild(scrollBarContainer);
  }

  // 清理引用
  delete el._stickyHeader;
  delete el.dataset.stickyInstanceId;
}